package initialize

import (
	"fmt"
	_ "github.com/mbobakov/grpc-consul-resolver"
	"go.uber.org/zap"
	"google.golang.org/grpc"
	"web/userop/global"
)

// 同时完成了服务发现和负载均衡算法（轮询）
func InitSrvConn(srvName string) *grpc.ClientConn {
	consulInfo := global.ServerConfig.ConsulInfo
	conn, err := grpc.Dial(
		fmt.Sprintf("consul://%s:%d/%s?healthy=true&wait=14s&tag=yg_shop",
			consulInfo.Host, consulInfo.Port, srvName),
		grpc.WithInsecure(),
		// grpc目前似乎只支持轮询的负载均衡算法
		grpc.WithDefaultServiceConfig(`{"loadBalancingPolicy": "round_robin"}`),
	)
	if err != nil {
		zap.S().Error("service层服务发现出错: ", err)
		return nil
	}
	return conn
}
